package com.roy88.serialportdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.roy88.serialportdemo.R.id.et_num;
import static com.roy88.serialportdemo.R.id.et_prot;

public class MainActivity extends Activity {

    @Bind(et_prot)
    EditText etProt;
    @Bind(et_num)
    EditText etNum;
    @Bind(R.id.btn_set)
    Button btnSet;
    @Bind(R.id.btn_open)
    Button btnOpen;
    @Bind(R.id.btn_send)
    Button btnSend;
    @Bind(R.id.btn_receive)
    Button btnReceive;
    @Bind(R.id.text_receive)
    TextView textReceive;


    protected SerialPort mSerialPort;
    protected InputStream mInputStream;
    protected OutputStream mOutputStream;

    private String prot = "ttyHSL1";
    private int baudrate = 9600;
    private static int i = 0;
    public static boolean flag = false;
    private StringBuilder sb;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                textReceive.setText(textReceive.getText().toString().trim() + sb.toString());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭串口
        closeSerialPort();
    }

    /**
     * 设置串口
     */

    private void setSerialInfo() {
        prot = TextUtils.isEmpty(etProt.getText().toString().trim()) ? prot
                : etProt.getText().toString().trim();
        baudrate = Integer.parseInt(TextUtils.isEmpty(etNum.getText()
                .toString().trim()) ? "115200" : etNum.getText()
                .toString().trim());
    }


    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.btn_set, R.id.btn_open, R.id.btn_send, R.id.btn_receive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_set://设置串口
                setSerialInfo();
                break;
            case R.id.btn_open://打开串口
                openSerialPort();
                break;
            case R.id.btn_send://发送串口数据
                sendSerialDate();
                break;
            case R.id.btn_receive://关闭串口
                closeSerialPort();
                break;
        }
    }



    /**
     * 打开串口
     */

    private void openSerialPort() {
        Log.i("test——serial", "打开串口");
        try {
            mSerialPort = new SerialPort(new File("/dev/" + prot), baudrate, 0);
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();

            flag = true;

            receiveSerialDate();

        } catch (SecurityException e) {
            e.printStackTrace();
            Log.i("test——serial", "打开失败");
        } catch (IOException e) {
            Log.i("test——serial", "打开失败");
            e.printStackTrace();
        }
        Log.i("test——serial # flag", "" +flag);
    }

    /**
     * 发送串口数据
     */

    private void sendSerialDate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    Log.i("test——serial", "发送串口数据");
                    try {
                        i++;
                        byte[] bytes = ("ok").getBytes();
                        mOutputStream.write(bytes);
                        mOutputStream.flush();
                        Log.i("test——serial", "发送成功:1" + i);
                        Thread.sleep(5000);
                    } catch (Exception e) {
                        Log.i("test——serial", "发送失败");
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 接收串口数据
     */

    private void receiveSerialDate() {
        sb = new StringBuilder();
        // 接收
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    int size;
                    try {
                        byte[] buffer = new byte[1024];
                        if (mInputStream == null) return;

                        size = mInputStream.read(buffer);
                        if (size > 0 && flag) {
                            String recinfo = new String(buffer, 0, size);
                            Log.i("test——serial接收到串口信息:", "8---" + recinfo);
                            sb.append(recinfo).append(",");
                            handler.sendEmptyMessage(1);
                        }
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        Log.i("test——serial", "关闭串口");
        i = 0;
        try {
            if (mSerialPort != null) {
                mSerialPort.close();
                Log.i("test——serial","关闭串口");
            }

            if(mInputStream != null) {
                mInputStream.close();
                Log.i("test——serial","关闭输入流");
            }
            if(mOutputStream != null){
                mOutputStream.close();
                Log.i("test——serial","关闭输出流");
            }
            flag = false;
            Log.i("test——serial","串口关闭成功");
        } catch (IOException e) {
            Log.i("test——serial","关闭串口失败");
            e.printStackTrace();
        }
    }
}
